package com.tengxing.e1.FactoryTest;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.maiarstar.e101.protocol.cerebellum.api.exception.ProtocolException;
import com.maiarstar.e101.protocol.cerebellum.api.model.MTQInfo;
import com.maiarstar.e101.protocol.cerebellum.api.module.ICerebellumProtocolGetter;
import com.maiarstar.e101.protocol.cerebellum.api.module.ICerebellumProtocolSetter;
import com.maiarstar.e101.protocol.cerebellum.sdk.CerebellumProtocolSdkManager;

public class MTQ_Test_Activity extends AppCompatActivity {
    private static final String TAG = "MTQ_Test_Activity";
    private CerebellumProtocolSdkManager cerebellumProtocolSdkManager;
    Button btn_MTQ_Pass, btn_MTQ_Fail,
            btn_MTQ1_On_P, btn_MTQ1_On_N, btn_MTQ1_Off,
            btn_MTQ2_On_P, btn_MTQ2_On_N, btn_MTQ2_Off,
            btn_MTQ3_On_P, btn_MTQ3_On_N, btn_MTQ3_Off,
            btn_MTQ_All_Off;
    TextView tV_MTQ_Status1, tV_MTQ_Status2, tV_MTQ_Status3;
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
    private Integer pwr, direction;
    private static Handler handler_refresh_status_task;
    private static Runnable run_refresh_status_task;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_mtq_test);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        sharedPreferences = getSharedPreferences("Test_Result", MODE_PRIVATE);
        tV_MTQ_Status1 = findViewById(R.id.tV_MTQ_Status1);
        tV_MTQ_Status2 = findViewById(R.id.tV_MTQ_Status2);
        tV_MTQ_Status3 = findViewById(R.id.tV_MTQ_Status3);

        initCerebellumManager();
        Factory_MTQ_BTN();
        Refresh_Status_Task_Init();
    }

    private void initCerebellumManager() {
        CerebellumProtocolSdkManager sdkProtocolManager = new CerebellumProtocolSdkManager(this);
        CerebellumProtocolSdkManager.SdkParams sdkParams = CerebellumProtocolSdkManager.getDeafultSdkParams();

        try {
            sdkProtocolManager.init(sdkParams);
        } catch (ProtocolException e) {
            Log.w(TAG, e.getMessage());
        }
        this.cerebellumProtocolSdkManager = sdkProtocolManager;
    }



    private void Factory_MTQ_BTN(){
        btn_MTQ_Pass = findViewById(R.id.btn_MTQ_Pass);
        btn_MTQ_Pass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor = sharedPreferences.edit();
                editor = editor.putString("MTQ","通过");
                if(editor.commit()){
                    Toast.makeText(MTQ_Test_Activity.this, "测试结果保存成功", Toast.LENGTH_SHORT).show();
                    SetMTQ(1, 0, 1);
                    SetMTQ(2, 0, 1);
                    SetMTQ(3, 0, 1);
                    Intent intent = new Intent(MTQ_Test_Activity.this, MainActivity.class);
                    startActivity(intent);
                    handler_refresh_status_task.removeCallbacks(run_refresh_status_task);//停止任务
                    finish();
                }else{
                    Toast.makeText(MTQ_Test_Activity.this, "测试结果保存失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_MTQ_Fail = findViewById(R.id.btn_MTQ_Fail);
        btn_MTQ_Fail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor = sharedPreferences.edit();
                editor = editor.putString("MTQ","未通过");
                if(editor.commit()){
                    Toast.makeText(MTQ_Test_Activity.this, "测试结果保存成功", Toast.LENGTH_SHORT).show();
                    SetMTQ(1, 0, 1);
                    SetMTQ(2, 0, 1);
                    SetMTQ(3, 0, 1);
                    Intent intent = new Intent(MTQ_Test_Activity.this, MainActivity.class);
                    startActivity(intent);
                    handler_refresh_status_task.removeCallbacks(run_refresh_status_task);//停止任务
                    finish();
                }else{
                    Toast.makeText(MTQ_Test_Activity.this, "测试结果保存失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_MTQ1_On_P = findViewById(R.id.btn_MTQ1_On_P);
        btn_MTQ1_On_P.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(SetMTQ(1, 1, 1)){
                    Toast.makeText(MTQ_Test_Activity.this, "设定成功", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MTQ_Test_Activity.this, "设定失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_MTQ1_On_N = findViewById(R.id.btn_MTQ1_On_N);
        btn_MTQ1_On_N.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(SetMTQ(1, 1, 0)){
                    Toast.makeText(MTQ_Test_Activity.this, "设定成功", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MTQ_Test_Activity.this, "设定失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_MTQ1_Off = findViewById(R.id.btn_MTQ1_Off);
        btn_MTQ1_Off.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(SetMTQ(1, 0, 1)){
                    Toast.makeText(MTQ_Test_Activity.this, "设定成功", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MTQ_Test_Activity.this, "设定失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_MTQ2_On_P = findViewById(R.id.btn_MTQ2_On_P);
        btn_MTQ2_On_P.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(SetMTQ(2, 1, 1)){
                    Toast.makeText(MTQ_Test_Activity.this, "设定成功", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MTQ_Test_Activity.this, "设定失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_MTQ2_On_N = findViewById(R.id.btn_MTQ2_On_N);
        btn_MTQ2_On_N.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(SetMTQ(2, 1, 0)){
                    Toast.makeText(MTQ_Test_Activity.this, "设定成功", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MTQ_Test_Activity.this, "设定失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_MTQ2_Off = findViewById(R.id.btn_MTQ2_Off);
        btn_MTQ2_Off.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(SetMTQ(2, 0, 1)){
                    Toast.makeText(MTQ_Test_Activity.this, "设定成功", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MTQ_Test_Activity.this, "设定失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_MTQ3_On_P = findViewById(R.id.btn_MTQ3_On_P);
        btn_MTQ3_On_P.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(SetMTQ(3, 1, 1)){
                    Toast.makeText(MTQ_Test_Activity.this, "设定成功", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MTQ_Test_Activity.this, "设定失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_MTQ3_On_N = findViewById(R.id.btn_MTQ3_On_N);
        btn_MTQ3_On_N.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(SetMTQ(3, 1, 0)){
                    Toast.makeText(MTQ_Test_Activity.this, "设定成功", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MTQ_Test_Activity.this, "设定失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_MTQ3_Off = findViewById(R.id.btn_MTQ3_Off);
        btn_MTQ3_Off.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(SetMTQ(3, 0, 1)){
                    Toast.makeText(MTQ_Test_Activity.this, "设定成功", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(MTQ_Test_Activity.this, "设定失败", Toast.LENGTH_SHORT).show();
                }
            }
        });


        btn_MTQ_All_Off = findViewById(R.id.btn_MTQ_All_Off);
        btn_MTQ_All_Off.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for(int i=1; i<4; i++){
                    if(!SetMTQ(i, 0, 1)){
                        Toast.makeText(MTQ_Test_Activity.this, "关闭失败", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

    }

    private boolean SetMTQ(Integer num, Integer pwr, Integer direction) throws ProtocolException {
        try {
            MTQInfo mtqInfo = new MTQInfo();
            mtqInfo.setOrder(num);
            mtqInfo.setPower(pwr);
            mtqInfo.setDirection(direction);
            ICerebellumProtocolSetter setter = this.cerebellumProtocolSdkManager.getCerebellumProtocolSetter();
            return setter.setMTQInfo(mtqInfo);
        } catch (Exception e) {
            Log.w(TAG, e.getMessage());
        }
        return false;
    }

    private boolean GetMTQ(Integer num) throws ProtocolException {
        try {
            ICerebellumProtocolGetter getter = this.cerebellumProtocolSdkManager.getCerebellumProtocolGetter();
            pwr = getter.getMTQInfo(num).getPower();
            direction = getter.getMTQInfo(num).getDirection();
            return true;
        } catch (Exception e) {
            Log.w(TAG, e.getMessage());
        }
        return false;
    }
    private void Refresh_Status_Task_Init(){
        handler_refresh_status_task = new Handler(Looper.getMainLooper());//新建任务
        run_refresh_status_task = new Runnable() {
            @Override
            public void run() {
                handler_refresh_status_task.postDelayed(this, 2000);
                Refresh_MTQ_Status(1, tV_MTQ_Status1);
                Refresh_MTQ_Status(2, tV_MTQ_Status2);
                Refresh_MTQ_Status(3, tV_MTQ_Status3);
                //Log.d(TAG, "Refresh_Status_Cycle:in");
            }
        };
        handler_refresh_status_task.post(run_refresh_status_task);//启动任务
        //Log.d(TAG, "Refresh_Status_Cycle:out");
    }
    private void Refresh_MTQ_Status(Integer num, TextView tV){

        pwr = -1; direction = -1;
        if(GetMTQ(num)){
            String str_status = "MTQ"+num+":";
            if(pwr == 1){
                str_status = str_status.concat("开启");
            } else if (pwr == 0) {
                str_status = str_status.concat("关闭");
            } else {
                tV.setText("获取失败");
            }

            if(direction == 1){
                str_status = str_status.concat("，正向");
            } else if (direction == 0) {
                str_status = str_status.concat("，反向");
            } else {
                tV.setText("获取失败");
            }
            tV.setText(str_status);
        }else{
            tV.setText("获取失败");
        }
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(MTQ_Test_Activity.this, MainActivity.class);
        SetMTQ(1, 0, 1);
        SetMTQ(2, 0, 1);
        SetMTQ(3, 0, 1);
        startActivity(intent);
        handler_refresh_status_task.removeCallbacks(run_refresh_status_task);//停止任务
        finish();
        Toast.makeText(MTQ_Test_Activity.this, "直接退出不会保存结果", Toast.LENGTH_SHORT).show();
        super.onBackPressed();
    }

}